package com.nulldev.util.web.nTube.util;

import java.io.EOFException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import com.nulldev.util.data.Variables;
import com.nulldev.util.internal.backport.httpclient_rw.HttpConnectTimeoutException;
import com.nulldev.util.internal.backport.httpclient_rw.HttpTimeoutException;
import com.nulldev.util.manage.nullUtil;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3.Request;

public class NTubeUtils {

	public static final boolean wasOriginHTTPS(final Request r) {
		if (r.hasHeader("Referer")) {
			return r.header("Referer", "").contains("https");
		} else if (r.hasHeader("Origin")) {
			return r.header("Origin", "").contains("https");
		} else {
			return r.protocolScheme().equalsIgnoreCase("https");
		}
	}

	public static boolean isSlientNetworkException(final Throwable error) {
		return isSlientNetworkException(error, false);
	}

	public static boolean isSlientNetworkException(final Throwable error, final boolean hasFallenThrough) {
		Variables.requireNonNull(error, "error");
		if (error instanceof RuntimeException && error.getCause() != null && !hasFallenThrough)
			return isSlientNetworkException(error.getCause(), true);
		if (nullUtil.DISABLE_ALL_SILENT_EXCEPTIONS)
			return false;
		return error instanceof HttpTimeoutException || error instanceof RuntimeException || error instanceof UnknownHostException
				|| error instanceof SocketTimeoutException || error instanceof ConnectException || error instanceof IllegalArgumentException
				|| error instanceof HttpConnectTimeoutException || error instanceof SSLHandshakeException || error instanceof EOFException
				// Workaround for OkHttp being annoying...
				|| (error instanceof IOException && error.getCause() instanceof EOFException);
	}
}
